//
//  TalkfunExaminationBtn.swift
//  TalkfunSDKDemo
//
//  Created by 莫瑞权 on 2021/12/2.
//  Copyright © 2021 Talkfun. All rights reserved.
//

import UIKit

class TalkfunExaminationBtn: UIView {
    var timer:Timer!
    var endTime:NSInteger = 0
    var  data :[TalkfunQuestionnaire] = []
    let imaegView = UIImageView()
    let titleLabel = UILabel()
    @objc public let btn = UIButton()
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.imaegView.image = UIImage.init(named: "HTLive.bundle/icon_test 2")
        self.addSubview(self.imaegView)
        
        self.titleLabel.text = "00:00:00"
        self.titleLabel.textAlignment = NSTextAlignment.center
        self.titleLabel.font = UIFont.PingFang(size: 10)
        self.titleLabel.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
        self.titleLabel.layer.masksToBounds = true
        self.titleLabel.isHidden = true
        self.titleLabel.textColor = UIColor(red: 1, green: 1, blue: 1,alpha:1)
        self.addSubview(self.titleLabel)
        
        
        self.addSubview(self.btn)
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        self.btn.frame = self.bounds

        self.imaegView.frame = CGRect(x: 1, y: 0, width: 40, height: 40)
        
        
        let titleY = self.imaegView.frame.size.height
        self.titleLabel.frame = CGRect(x: 0, y: titleY, width: 42, height: 16)
        self.titleLabel.layer.cornerRadius = 8
        
        
        
    }
    //结束其中一个
    @objc public func deleteUI(_ model:TalkfunQuestionnaire)
    {
        
        for i in stride(from: 0, to: self.data.count ,by: 1) {
            let number = self.data[i] as TalkfunQuestionnaire
            if number.id == model.id {
                
                number.endTime = TalkfunSharedTools.getCurrentDateString()
            }
          
        }

        self.titleLabel.text = "00:00:00"
        self.updateDisplay()
    }
    //添加单个试卷
    @objc public func addModel(_ model:TalkfunQuestionnaire)
    {
        if self.isHidden {
            self.isHidden = false
        }
        
    
        self.data.append(model)
        //从小到大排序
        self.data.sort(by: { (number1: TalkfunQuestionnaire, number2: TalkfunQuestionnaire) -> Bool in return number1.endTime < number2.endTime })
    
        self.updateDisplay()
    }
    //添加试卷列表
    @objc public func addData(_ result:TalkfunQuestionnaireResult)
    {
        self.data.removeAll()

        //从小到大排序
        result.data.sort(by: { (number1: TalkfunQuestionnaire, number2: TalkfunQuestionnaire) -> Bool in return number1.endTime < number2.endTime })
    
        
        for i in stride(from: 0, to: result.data.count ,by: 1) {
            let number = result.data[i]
            self.data.append(number)
        }
        
        self.updateDisplay()

    }
    @objc public func updateDisplay()
    {
        if ( self.data.count > 0)
        {
            self.data.sort(by: { (number1: TalkfunQuestionnaire, number2: TalkfunQuestionnaire) -> Bool in return number1.endTime < number2.endTime })
            
            let newList = NSMutableArray()
            
            for i in stride(from: 0, to: self.data.count ,by: 1) {
                
                let model = self.data[i]
                ///**参与状态 - 1 未参加   0 已参加 ,但未提交、1已提交、2已批阅*/
                if (model.answerStatus != TalkfunAnswerStatusSubmitted && model.endTime > TalkfunSharedTools.getCurrentDateString() && (model.answerStatus != TalkfunAnswerStatusApproved))
                {
                    newList.add(model)
                    
                }
                
            }
            
            if newList.count > 0 {
                if self.isHidden {
                    self.isHidden = false
                }
               
                let model = newList[0] as! TalkfunQuestionnaire
                if model.type == TFExaminationTypeTestPaper {
                    self.titleLabel.isHidden = false
                }
                
                self.addModel(endTime: model.endTime)
            }else
            {

                self.titleLabel.text = "00:00:00"
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(1)) {
                // do something
                    self.timerInvalidate()
                }
               
            }
            
            
        }
        
    }
    
    @objc public func addModel(endTime:NSInteger)
    {
        self.endTime = endTime
        self.initTimer()
    }
    
    
    func initTimer()
    {
        if((self.timer) == nil)
        {
            self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(startCountdown), userInfo: nil, repeats: true)
            RunLoop.main.add(self.timer! , forMode: RunLoop.Mode.default)
            self.timer.fire()
        }
    }
    
    @objc func startCountdown() {
        
        if (TalkfunSharedTools.getCurrentDateString() <  self.endTime)
        
        {
            let countdownStr = TalkfunSharedTools.timeDifference(endTime: self.endTime)

          
            
            self.titleLabel.text = countdownStr as String
            
        }else
        {

            self.titleLabel.text = "00:00:00"
            self.updateDisplay()
        }
        
     
    }
    

    //结束定时器
    @objc func timerInvalidate()
    {
        if((self.timer) != nil)
        {
            self.timer.invalidate()
            self.timer = nil
        }

        self.titleLabel.isHidden = true
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        fatalError("init(coder:) has not been implemented")
    }
}
